var app = getApp();
var core = app.requirejs('core');
// var parser = app.requirejs('wxParse/wxParse');//
var diypage = app.requirejs('biz/diypage'); //自定义页面
var diyad = app.requirejs('biz/ad');
// var diyform = app.requirejs('biz/diyform');
// var goodspicker = app.requirejs('biz/goodspicker');
// var mainui = app.requirejs('mainui');//购买最大最小值
var $ = app.requirejs('jquery');
const api = require("../../utils/api.js")
Page(app.sr.page({
  data: {
    indicatorDotss: true,
    autoplays: true,
    intervals: 2000,
    durations: 500,
    circulars: true,
    adveradmin: true,
    current: 0, //商品组翻页 
    clock: '',
    /*广告结束*/
    diypage: 'true',
    route: 'home',
    shop: {},
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 500,
    circular: true,
    /* 店铺推荐列表 */
    storeRecommand: [],
    total: 1,
    page: 1,
    loaded: false,
    loading: true,
    /*滚动*/
    indicatorDotsHot: false,
    autoplayHot: true,
    intervalHot: 5000,
    durationHOt: 1000,
    circularHot: true,
    hotimg: "/static/images/hotdot.jpg",
    notification: "/static/images/notification.png",
    saleout1: "/static/images/saleout-1.png",
    saleout2: "/static/images/saleout-2.png",
    saleout3: "/static/images/saleout-3.png",
    play: "/static/images/video_play.png",
    mute: "/static/images/icon/mute.png",
    voice: "/static/images/icon/voice.png",
    // 购物车
    specs: [],
    options: [],
    diyform: {},
    specsTitle: '',
    total: 1,
    active: '',
    slider: '',
    tempname: '',
    buyType: '',
    areas: [],
    closeBtn: false,
    soundpic: true,

    modelShow: false,
    limits: true,
    result: {},
    showcoupon: false,
    showcoupontips: false,
    topmenu: {},
    topmenuDataType: '',
    tabbarData: {},
    tabbarDataType: '',
    istopmenu: false,
    //秒杀组
    seckillinfo: {},
    timer: 0,
    lasttime: 0,
    hour: '-',
    min: '-',
    sec: '-',
    // 选项卡默认
    xxqactiveid: 0,
    searchValue: ''
  },
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
    // var $this = this
    // diypage.get(this, 'home', function(res) {

    //   $this.getDiypage(res)
    //   if (res.error == 0) {
    //     wx.stopPullDownRefresh()
    //   }
    // })
  },
  //输入搜索值
  iChange: function (e) {
    var value = e.detail.value;
    this.setData({
      searchValue: value
    })
  },
  //向输入框输入值时出发事件
  //搜索
  searchBtn: function (e) {
    let $this = this
    wx.showLoading({
      title: '搜索中',
    })
    console.log(e)
    let keyword = e.currentTarget.dataset.placeholder
    let keywords = ''
    if ($this.data.searchValue) {
      keywords = $this.data.searchValue
    } else {
      $this.setData({
        searchValue: keyword
      })
      keywords = keyword
    }
    //sdk
    app.sr.track('search', {
      "keyword": $this.data.searchValue,
      // more...
    })
    let apicontent = api.goods.searchGoods()
    core.post(apicontent, {
      keywords: $this.data.searchValue
    }, function (res) {
      wx.hideLoading();
      if (res.data.rows.length > 0) {
        wx.navigateTo({
          url: '/pages/goods/searchlist/index?value=' + $this.data.searchValue,
        })
      } else {
        wx.showToast({
          title: '暂无搜索结果',
          icon: 'none',
          image: '/static/images/icon_error.png',
          duration: 2000
        })
      }
    })
  },
  //定制服务
  dingzhifuwu: function (e) {
    var id = e.target.dataset.index;
    if (id == 4) {
      wx.navigateTo({
        url: '../christmas/christmas',
      })
    }
  },
  //不知道用处
  toShopDetail(e) {
    let shopId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/goods/detail/index?id=' + shopId,
    })
  },

  /* 获取首页信息 */
  //不知道用处
  getShop: function () {
    var $this = this;
    core.get('shop/get_shopindex', {}, function (result) {


      parser.wxParse('wxParseData', 'html', result.copyright, $this, '5');
      $this.setData({
        shop: result
      });
    });
  },
  onLoad: function (options) {
    wx.hideTabBar({
      // animation: true,
    })
    options = options || {};
    var $this = this;
    // 处理扫码scene
    var scene = decodeURIComponent(options.scene);
    if (!options.id && scene) {
      var sceneObj = core.str2Obj(scene);
      options.id = sceneObj.id;
      if (sceneObj.mid) {
        options.mid = sceneObj.mid;
        app.setCache('usermid', sceneObj)
      }
    }
    app.url(options);
    $this.setData({
      cover: true,
      showvideo: false
    });
    wx.getSystemInfo({
      success: function (res) {
        var swiperheight = res.windowWidth / 1.7
        $this.setData({
          swiperheight: swiperheight
        })
      }
    });
  },

  onHide: function () {
    this.setData({
      adveradmin: false,
      unpaid: false
    });
  },

  onShow: function () {
    // app.checkAuth();
    let _this = this
    _this.initFunction()
  },

  initFunction: function () {
    var $this = this;
    let mobile = wx.getStorageSync('mobile');
    app.miniprogram(function (res) {
      // 判断是否维护中
      if (res.isVindicate == 0) {

        $this.setData({
          isVindicate: true
        })
      } else {
        $this.setData({
          isVindicate: false
        })
      }
      //判断是否显示客服悬窗
      let globalData = app.globalData


      $this.setData({
        globalData: globalData
      })
      //判断是否进入首页绑定节点
      if (res.bindingNodes == 3) {
        if (mobile.length < 1) {
          core.alert("请绑定手机", function () {

            wx.navigateTo({
              url: '/pages/member/bind/index',
            })
          })
          return
        }
      }


    })
    var res = wx.getSystemInfoSync()
    var sysset = app.getCache('sysset');
    let currentUrl = app.getCache("currentUrl")
    if (currentUrl.includes('goods/detail/index')) {
      if (currentUrl.includes('_')) {
        // 拦截参数
        let params = currentUrl.split('_')
        let type = params[1]
        let url = params[0]
        if (type == 'auth') {
          app.removeCache('currentUrl')
          let newUrl = url
          wx.navigateTo({
            url: newUrl,
          })
        }
      }
    }
    // wx.getSetting({
    //   success: function (res) {
    //     var limits = res.authSetting['scope.userInfo'];
    //   }
    // })

    /*自定义页面*/ //设置自定义页面的 顶部基础信息
    diypage.get(this, 'home', {}, function (res) {
      // $this.getDiypage(res)

      var pagetitle = sysset.shopname || '商城首页';
      if ($this.data.diypages) {
        let page = $this.data.diypages
        wx.setNavigationBarTitle({
          title: page.basicOption.pageTitle
        });
        wx.setNavigationBarColor({
          frontColor: page.basicOption.tabColor == 'white' ? '#ffffff' : '#000000',
          backgroundColor: page.basicOption.tabBackColor,
        })
      }
    })
    /**启动广告 */
    diyad.get(this, function (res) { })
    // $this.setData({
    //   screenWidth: res.windowWidth
    // });
  },
  // goodsicon: function (e) {
  //   this.setData({
  //     iconheight: e.detail.height,
  //     iconwidth: e.detail.width
  //   })
  // },
  // getDiypage: function (res) {
  //   var $this = this;
  //   let items = JSON.parse(res.diypage.data)
  //   $.each(items, function (id, item) {
  //     if (item.id == 'topmenu') {
  //       $this.setData({
  //         topmenu: item
  //       });
  //       if (item.data[0] == undefined) {
  //         var linkurl = '';
  //       } else {
  //         var linkurl = item.data[0].linkurl;
  //         core.get('diypage/getInfo', {
  //           dataurl: linkurl
  //         }, function (ret) {

  //           item.data[0].data = ret.goods.list;
  //         });
  //       }

  //     }

  //     if (item.id == 'seckillgroup') {
  //       var data = {};
  //       data.status = item.data.status;
  //       data.endtime = item.data.endtime;
  //       data.starttime = item.data.starttime;
  //       $this.initSeckill(data);
  //     }
  //   });

  // },
  onShareAppMessage: function () {
    var url = null;
    var title = null;
    if (this.data.diytitle) {
      url = '/pages/index/index'
      title = this.data.diytitle
    }
    return core.onShareAppMessage(url, title);
  },

  onShareTimeline: function (res) {
    return {
      title: this.data.diytitle,
      query: ''
    }
  },
  //获取图片高度
  imagesHeight: function (e) {
    var width = e.detail.width,
      height = e.detail.height,
      type = e.target.dataset.type,
      $this = this;

    var isdot = e.currentTarget.dataset.isdot
    wx.getSystemInfo({
      success: function (res) {
        if (isdot == "dot_inside") {
          $this.data.result[type] = Number(res.windowWidth / width * height);
        } else {
          $this.data.result[type] = Number(res.windowWidth / width * height) + 30;

        }
        if (!$this.data[type] || ($this.data[type] && result[type] < $this.data[type])) {
          $this.setData({
            result: $this.data.result
          });
        }
      }
    });
  },
  bindInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  // t1: function (e) {
  //   diypage.fixedsearch(this, e);
  // },
  //开始播放
  startplay: function (e) {
    var cover = e.target.dataset.cover;
    this.setData({
      cover: cover,
      showvideo: true
    });
    this.videoContext = wx.createVideoContext('Video');
    this.videoContext.play()
  },
  changevoice: function () {
    if (this.data.sound) {
      this.setData({
        sound: false,
        soundpic: true
      })
    } else {
      this.setData({
        sound: true,
        soundpic: false
      })
    }
  },
  phone: function () {
    var phoneNumber = this.data.phonenumber + ''
    wx.makePhoneCall({
      phoneNumber: phoneNumber
    })
  },
  navigate: function (e) {
    var phone = e.currentTarget.dataset.phone
    var appid = e.currentTarget.dataset.appid
    var appurl = e.currentTarget.dataset.appurl
    var url = e.currentTarget.dataset.url

    if (url.includes('?cate')) {
      let params = url.split('?')
      if (params[1].includes('cate')) {
        let cateid = params[1].split('=')[1]

        app.setCache("cateid", cateid)
      }
      wx.switchTab({
        url: url,
      })
    } else {
      wx.navigateTo({
        url: url,
        fail: function () {
          wx.switchTab({
            url: url,
          })
        }
      })
    }
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone
      })
    }
    if (appid) {
      wx.navigateToMiniProgram({
        appId: appid,
        path: appurl
      })
    }
  },
  userinfo: function (e) {
    var iv = e.detail.iv;
    var encryptedData = e.detail.encryptedData;
    app.getUserInfo(null, null, {
      iv: iv,
      encryptedData: encryptedData
    });
  },
  close: function () {
    app.globalData.flag = true;
    wx.reLaunch({
      url: '../index/index',
    })
  },
  formatSeconds: function (value) {
    var theTime = parseInt(value);
    var theTime1 = 0;
    var theTime2 = 0;
    if (theTime > 60) {
      theTime1 = parseInt(theTime / 60);
      theTime = parseInt(theTime % 60);
      if (theTime1 > 60) {
        theTime2 = parseInt(theTime1 / 60);
        theTime1 = parseInt(theTime1 % 60)
      }
    }
    return {
      'hour': theTime2 < 10 ? '0' + theTime2 : theTime2,
      'min': theTime1 < 10 ? '0' + theTime1 : theTime1,
      'sec': theTime < 10 ? '0' + theTime : theTime
    }
  },
  // 店铺装修商品组件
  cutGoods: function (e) {
    var $this = this,
      type = e.currentTarget.dataset.type,
      num = e.currentTarget.dataset.num,
      id = e.currentTarget.dataset.id,
      diypages = $this.data.diypages;
    for (var i in diypages.items) {
      if (i == id) {
        var current = diypages.items[i].current || 0;
        if (type == 'advance') {
          if (current < num - 1) {
            diypages.items[i].current = current + 1;
            $this.setData({
              diypages: diypages
            })
          } else {
            diypages.items[i].current = 0;
            $this.setData({
              diypages: diypages
            })
          }
        } else {
          if (current > 0) {
            diypages.items[i].current = current - 1;
            $this.setData({
              diypages: diypages
            })
          } else {
            diypages.items[i].current = num - 1;
            $this.setData({
              diypages: diypages
            })
          }
        }
      }
    }

  },
  //banner 图点的样式
  changeBanner(e) {
    this.setData({
      current: e.detail.current
    })
  },
  // 选择选项卡
  changexuanxiangqia(e) {

    this.setData({
      xxqactiveid: e.target.dataset.id
    })
  },

  // 广告关闭 
  closeAdver() {
    this.setData({
      showAdver: false
    })
  },

  // 路由跳转
  navigateMf(e) {
    var url = e.currentTarget.dataset.url
    var re = /^[0-9]+.?[0-9]*/; //判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/ 

    //跳转其他小程序
    if (url.appid) {


      wx.navigateToMiniProgram({
        appId: url.appid,
        path: url.urldata,
        extraData: {
          // foo: 'bar'
        }, //跳转到其他小程序传递的参数
        envVersion: 'develop',
        success(res) {
          console.log(url.urldata)
        },
        fail(res) {
        }
      })
    } else if (url.includes('?cate')) {
      let params = url.split('?')
      if (params[1].includes('cate')) {
        let cateid = params[1].split('=')[1]

        app.setCache("cateid", cateid)
      }
      wx.switchTab({
        url: url,
      })
    } else if (re.test(url)) {


      wx.makePhoneCall({
        phoneNumber: url //仅为示例，并非真实的电话号码
      })
    } else if (url == '/pages/index/index') {
      wx.switchTab({
        url: url,
      })
    } else {
      wx.navigateTo({
        url: url,
        fail: function () {
          wx.switchTab({
            url: url,
          })
        }
      })
    }
  },
  // 小程序店铺配置，小程序是否维护
  miniprogram() {
    let $this = this
    let apicontent = api.members.getminiprogram()
    core.post(apicontent, {}, function (res) {
      if (res.isVindicate == 0) {

        $this.setData({
          isVindicate: true
        })
      } else {
        $this.setData({
          isVindicate: false
        })
      }
    })
  },
  //电话客服
  TelephoneService() {

    wx.makePhoneCall({
      phoneNumber: '12121' //仅为示例，并非真实的电话号码
    })
  }
}));